import 'dart:async';
import 'package:logger/logger.dart';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/foundation.dart';

import 'api.dart';
import 'http_helper.dart';

/// 网络请求管理类
class Http {
  static Http _instance;
  Dio dio;

  /// 单例模式
  static Http getInstance(
      {baseUrl = serviceBaseUrl, authorization = bearerAuthorization}) {
    if (_instance == null) {
      _instance = Http(baseUrl: baseUrl, authorization: authorization);
    }
    return _instance;
  }

  // 构造函数,初始化 options
  Http({baseUrl = serviceBaseUrl, authorization = bearerAuthorization}) {
    BaseOptions options = new BaseOptions(
      //请求基地址,可以包含子路径
      baseUrl: baseUrl,
      //连接服务器超时时间，单位是毫秒.
      connectTimeout: 1000 * 600,
      //响应流上前后两次接受到数据的间隔，单位为毫秒。
      receiveTimeout: 1000 * 600,
      responseType: ResponseType.json,
    );
    options.headers['Content-Type'] = 'application/json';
    options.headers['Authorization'] = authorization;
    // 创建dio
    dio = new Dio(options);
    //  是否开启请求日志
    // dio.interceptors.add(LogInterceptor());
    //  缓存相关类
    dio.interceptors.add(CookieManager(CookieJar()));
    //  添加拦截器
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (RequestOptions options) {
          debugPrint(
              '---api--request(${options.method})--->url--> ${options.baseUrl}${options.path}' +
                  ' data: ${options.data}' +
                  ' queryParameters: ${options.queryParameters}');
          return options;
        },
        onResponse: (Response response) {
          ResponseData respData = ResponseData.fromJson(response.data);
          if (respData.isSuccess) {
            response.data = respData?.data;
            print('---------------- 返回的数据 ----------------');
            Logger().d(response.data);
            return dio.resolve(response);
          } else {
            print('---------------- NotSuccessException ----------------');
            throw NotSuccessException.fromRespData(respData);
          }
        },
        onError: (DioError error) {
          return error;
        },
      ),
    );
  }

  /// get请求
  Future get(String url, {params}) async {
    try {
      Response response;
      response = await dio.get(url, queryParameters: params);
      return response.data;
    } on DioError catch (error) {
      if (error.error is NotSuccessException) {
        NotSuccessException e = error.error as NotSuccessException;
        _formatError(e.message);
        throw e;
      } else {
        _formatError('服务器错误');
        throw error;
      }
    }
  }

  /// post请求
  Future post(
    String url,
    data,
  ) async {
    try {
      Response response;
      response = await dio.post(
        url,
        data: data,
      );
      return response.data;
    } on DioError catch (error) {
      if (error.error is NotSuccessException) {
        NotSuccessException e = error.error as NotSuccessException;
        _formatError(e.message);
        throw e;
      } else {
        _formatError('服务器错误');
        throw error;
      }
    }
  }

  /// DioError统一处理
  void _formatError(String e) {
    print(e);
  }
}

/// 数据转化
class ResponseData extends BaseResponseData {
  bool get isSuccess => status == 200 || code == 200;

  ResponseData.fromJson(Map<String, dynamic> json) {
    message = json['message'];
    errors = json['errors'];
    status = json['status'];
    data = json['data'];
    code = json['code'];
  }
}
